var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

var usersRouter = require("./routes/users");
var commentsRouter = require("./routes/comments");
var articleRouter = require("./routes/article");
var categoryRouter = require("./routes/category");

var app = express();

// 解决跨域
const cors = require("cors");
app.use(cors());
// 注册
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
var dashboardRouter = require("./routes/dashboard");
// 引入七牛云请求配置
const qnconfig = require("./config/qiuniu");

/**
 * 在路由之前配置及解析token
 */
// 导入joi包
const joi = require("joi");
const { expressjwt: expressJwt } = require("express-jwt");
const { token, info } = require("./config");
//注册中间件
app.use(
  expressJwt({ secret: token.jwtSecretKey, algorithms: ["HS256"] }).unless({
    path: [
      /^\/users\/login/,
      /^\/users\/regUser/,
      /^\/article\/getArticle/,
      /^\/category\/getName/,
      /^\/article\/getHotArticle/,
      /^\/article\/getRecommend/,
      /^\/article\/getSingleArt/,
      /^\/comments\/getAllComments/,
    ],
  })
);

/**
 * 定义一个中间件
 * 用来重新刷新token
 */
// 导入生成token字符串的包
const jwt = require("jsonwebtoken");
app.use((req, res, next) => {
  // 排除登录注册接口
  if (req.url.includes("login") || req.url.includes("regUser")) {
    next();
    return;
  }
  if (req.auth) {
    const user = {
      id: req.auth.id,
      username: req.auth.username,
      password: "",
      avatar: "",
    };
    let newToken = jwt.sign(user, token.jwtSecretKey, {
      expiresIn: token.expiresIn,
    });
    res.setHeader("Access-Control-Expose-Headers", "Authorization");
    res.header("Authorization", newToken);
    next();
    return;
  }
  next();
});

// 七牛云请求
// 七牛云获取token
app.get("/token", (req, res, next) => {
  res.status(200).send(qnconfig.uploadToken);
});
// 七牛云删除图片
app.post("/qiniuDel", (req, res, next) => {
  const { key } = req.body;
  // console.log(req.body);
  const bucket = "image-wsh";
  qnconfig.bucketManager.delete(bucket, key, (err, respBody, respInfo) => {
    if (err) {
      console.log(err);
    } else {
      // console.log(respInfo.statusCode);
      // console.log(respBody);
      if (respBody == null) {
        res.send(info(0, "删除成功", ""));
      }
    }
  });
});
// 注册路由
app.use("/users", usersRouter);
app.use("/comments", commentsRouter);
app.use("/article", articleRouter);
app.use("/category", categoryRouter);
app.use("/dashboard", dashboardRouter);
// 定义一个错误中间件
app.use((err, req, res, next) => {
  // 验证数据失败导致的错误
  if (err instanceof joi.ValidationError)
    return res.send(info(1, "用户名或密码不符合规定", err.message));
  // token认证失败的错误
  if (err.name === "UnauthorizedError") {
    // console.log(401);
    return res.status(401).send(info(1, "无效token", ""));
  }
  // 未知错误
  res.send(info(1, "未知错误", err.message));
});

module.exports = app;
